package org.opsli.plugins.qr;

import cn.hutool.extra.qrcode.QrCodeUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Api(tags = "二维码生成")
@Slf4j
@RestController
public class QRController {

    // TODO 二维码生成
    @GetMapping("/QR")
    public void generateQRCode(String str, HttpServletResponse response) throws IOException {
        log.info("生成二维码 QR code for: {}", str);

        // 生成二维码图片
        BufferedImage qrImage = QrCodeUtil.generate(str, 300, 300);

        // 设置响应类型为PNG
        response.setContentType("image/png");

        // 将BufferedImage写入响应流
        try (OutputStream os = response.getOutputStream()) {
            ImageIO.write(qrImage, "PNG", os);
            os.flush();
        } catch (Exception e) {
            log.error("Failed to generate QR code", e);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "QR code generation failed");
        }
    }
}
